package com.whmnx.chitchat.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;


import com.whmnx.chitchat.bean.AuthRequest;
import com.whmnx.chitchat.bean.SendMessage;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Administrator
 */
public class ReliableClient {
    private final int ECHO_NUM      =  1001;
    private final int RECEIVE_NUM   =  1002;
    private final int KICKOUT_NUM   =  1003;
    private final int AUTH_NUM      =  1004;
    private final int CHECKAUTH_NUM =  1005;
    private final int OTHERCONNECTIONCHANGED_NUM = 1006;

    private long curRecvSeq = -1;
    private long processTime = System.currentTimeMillis();

    private Context context;
    private String url;
    public SignalRChannel signalRChannel;
    //登录信息，用于重连时自动登录。
    private AuthRequest authMessage = null;
    private String TAG = getClass().getSimpleName();
    //创建消息队列
    private Queue<SendMessage> sendMessageQueue = new LinkedList<SendMessage>();
    //连接状态属性
   private volatile boolean isRunning = true;



    public ReliableClient(String url1, Context context) {
        this.url = url1;
        this.context = context;
        Thread t = new Thread(runnableSend);
        t.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler receiveHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case ECHO_NUM:
                    Log.i(TAG,"echo handler");
                    String msgJosn = msg.obj.toString();
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.ACCEPTMSG);
                    messageEvent.setMessageValue(msgJosn);
                    EventBus.getDefault().post(messageEvent);

                    try {
                        JSONObject jsonObject = new JSONObject(msgJosn);
                        String groupId = jsonObject.getString(Constants.GROUPID);
                        //发送者
                        String sendId = jsonObject.getString(Constants.SENDID);
                        if (!TextUtils.isEmpty(groupId) || !groupId.contains("null")){
                            String id = SPUtil.getString(Constants.USERID);
                            if (!sendId.equals(id)) {
                                UItils.playRingTone();
                            }
                        }else {
                            UItils.playRingTone();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Log.i(TAG,msgJosn.toString());
                   // receiveMessage(msg);
                    break;
                case RECEIVE_NUM:
                    String msgJosn2 = msg.obj.toString();
                    MessageEvent messageEvent2 = new MessageEvent();
                    messageEvent2.setMessageKey(EventConstants.ACCEPTMSG2);
                    messageEvent2.setMessageValue(msgJosn2);
                    EventBus.getDefault().post(messageEvent2);
                  //  receiveMessage(msg);
                    Log.i(TAG,msgJosn2.toString());
                    break;
                default:
            }
        }
    };

    private String nowTime() {
        String timeStr = null;
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年-MM月dd日-HH时mm分ss秒 ");
        timeStr = dateFormat.format(date);
        return timeStr;
    }

    // 收到receive的消息后的处理
    // 无脑回ack，
    // 然后消息去重，
    // 存入数据库
    // 顺序化
    // 等待时间过长，取最小的处理。
    private void receiveMessage(Message msg) {

    }

    public boolean isConected(){
        return signalRChannel.isConnected();
    }

    /***/
    private Runnable runnableSend = new Runnable() {
        @Override
        public void run() {
            while(isRunning){
                try {
//                    connectStatus = signalSession.isConnectStatus();
                    //刷新连接状态
                    if(signalRChannel == null || !signalRChannel.isConnected()){
                        try{
                            reConnect();
                        }catch (Exception e){
                            e.printStackTrace();
                            continue;
                        }
                    }
                    while(!sendMessageQueue.isEmpty()){
                        //发送消息
                        SendMessage sendMessage = sendMessageQueue.poll();
                        signalRChannel.send(sendMessage.method, sendMessage.message);
                    }
                   // Thread.sleep(4000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 重连机制
     * 1. 调用登出，断开连接
     * 2. 重新建立连接
     * 3. 如果是在登录状态下，重新登录
     * */
    private void reConnect() {
        if(signalRChannel != null){
            signalRChannel.stopConnect();
        }
        signalRChannel = new SignalRChannel(url,receiveHandler);
        signalRChannel.startConnect();
    }

    /**
     * 开放给外部的四个方法
     * 1. 发送消息 send
     * 2. 登录 LogIn
     * 3. 登出 LogOut
     * 4. 发送接收的消息走handler
     * */

    //发送消息
    public void send(String method, Object... messages){
        /**
         * queue
         * */
        if(method.equals("Echo")){
            long time = System.currentTimeMillis()/1000;
            signalRChannel.send(method, String.valueOf(time/1000));
        }else {
            SendMessage sendMessage = new SendMessage(method,messages);
            sendMessageQueue.offer(sendMessage);
        }
    }

    //登录
    public void LogIn(AuthRequest authRequest){
        this.authMessage = authRequest;
        //todo: write file
//        signalRChannel.send("Auth",authMessage);

    }

    //登出
    public void LogOut(){
      //  authMessage = null;
        if(signalRChannel != null){
            signalRChannel.stopConnect();
        }
    }
}
